# item_viewer.py
import tkinter as tk
from tkinter import ttk, messagebox
import webbrowser
import configparser
import os
from data_loader import load_data
from item_detail_window import ItemDetailWindow
from global_calculator import BaseMaterialEditor, MultiItemCalculator
from settings_applier import apply_settings
from settings_window import SettingsWindow  # 导入设置窗口

# 加载数据
data, base_materials, id_to_name, all_item_ids = load_data()

class ItemViewer:
    def __init__(self, root, settings=None):
        self.root = root
        self.settings = settings or {}
        self.root.title("粘液科技物品查看器 by bilibili星環工程師")
        self.root.geometry("800x600")
        
        # 应用设置到主窗口
        self.apply_settings(self.root, self.settings)
        
        # 菜单栏
        self.menu_bar = tk.Menu(root)
        
        # 编辑菜单
        edit_menu = tk.Menu(self.menu_bar, tearoff=0)
        edit_menu.add_command(label="更改基础物品名单", command=self.edit_base_materials)
        edit_menu.add_separator()
        edit_menu.add_command(label="设置", command=self.open_settings)
        self.menu_bar.add_cascade(label="编辑", menu=edit_menu)
        
        # 计算菜单
        calc_menu = tk.Menu(self.menu_bar, tearoff=0)
        calc_menu.add_command(label="多物品材料计算", command=self.multi_item_calculation)
        self.menu_bar.add_cascade(label="计算", menu=calc_menu)
        
        # 关于菜单
        about_menu = tk.Menu(self.menu_bar, tearoff=0)
        about_menu.add_command(label="作者官网", command=lambda: self.open_url("https://space.bilibili.com/3493137687251407"))
        about_menu.add_command(label="程序仓库", command=lambda: self.open_url("https://gitee.com/StarRingEngr/slimefun-recipe-assistant"))
        about_menu.add_command(label="反馈建议", command=lambda: self.open_url("https://gitee.com/StarRingEngr/slimefun-recipe-assistant/issues"))
        about_menu.add_separator()
        about_menu.add_command(label="关于程序", command=self.show_about)
        self.menu_bar.add_cascade(label="关于", menu=about_menu)
        
        root.config(menu=self.menu_bar)
        
        # 搜索框架
        search_frame = ttk.Frame(root)
        search_frame.pack(pady=10, padx=10, fill=tk.X)
        
        ttk.Label(search_frame, text="搜索物品:").pack(side=tk.LEFT, padx=(0, 5))
        
        self.search_var = tk.StringVar()
        self.search_entry = ttk.Entry(search_frame, textvariable=self.search_var, width=40)
        self.search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        self.search_entry.bind("<KeyRelease>", self.update_search)
        
        # 结果列表
        self.result_frame = ttk.Frame(root)
        self.result_frame.pack(pady=5, padx=10, fill=tk.BOTH, expand=True)
        
        self.tree = ttk.Treeview(self.result_frame, columns=("name", "id"), show="headings")
        self.tree.heading("name", text="物品名称")
        self.tree.heading("id", text="ID")
        self.tree.column("name", width=300)
        self.tree.column("id", width=300)
        
        vsb = ttk.Scrollbar(self.result_frame, orient="vertical", command=self.tree.yview)
        hsb = ttk.Scrollbar(self.result_frame, orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        
        self.tree.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")
        
        self.tree.bind("<Double-1>", self.show_details)
        self.tree.bind("<Return>", self.show_details)
        
        # 网格布局
        self.result_frame.columnconfigure(0, weight=1)
        self.result_frame.rowconfigure(0, weight=1)
        
        # 状态栏
        self.status = ttk.Label(root, text="", relief=tk.SUNKEN, anchor=tk.W)
        self.status.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 初始化显示
        self.update_search()
        
        # 窗口关闭事件
        root.protocol("WM_DELETE_WINDOW", self.on_close)

    def apply_settings(self, window, settings):
        """应用设置到窗口 - 使用外部函数"""
        apply_settings(window, settings)

    def edit_base_materials(self):
        """编辑基础物品名单"""
        # 传递设置给子窗口
        editor = BaseMaterialEditor(self.root,settings=self.settings)
    
    def open_settings(self):
        """打开设置窗口"""
        SettingsWindow(self.root, self.settings)
    
    def multi_item_calculation(self):
        """多物品材料计算"""
        # 传递设置给子窗口
        calculator = MultiItemCalculator(self.root,settings=self.settings)
    
    def open_url(self, url):
        """打开指定URL"""
        try:
            webbrowser.open_new(url)
        except Exception as e:
            messagebox.showerror("打开链接失败", f"无法打开链接:\n{url}\n错误: {str(e)}")
    
    def show_about(self):
        """显示关于对话框"""
        about_text = (
            "粘液科技物品查看器\n"
            "版本: V0.4.2\n\n"
            "开发者: bilibili星環工程師\n"
            "本程序用于查看和浏览粘液科技(Slimefun)中的物品数据\n\n"
            "© 2025 星環工作室 保留所有权利"
        )
        messagebox.showinfo("关于", about_text)
    
    def on_close(self):
        """主窗口关闭时的处理"""
        for child in self.root.winfo_children():
            if isinstance(child, tk.Toplevel):
                child.destroy()
        self.root.destroy()

    def update_search(self, event=None):
        """根据搜索词更新结果列表"""
        search_term = self.search_var.get().lower()
        
        # 清空当前列表
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # 添加匹配项
        for item in data:
            if search_term in item["name"].lower() or search_term in item["id"].lower():
                self.tree.insert("", "end", 
                                values=(item["name"], item["id"]), 
                                iid=item["id"])
        
        # 更新状态栏
        self.status.config(text=f"已加载 {len(data)} 个物品 | 找到 {len(self.tree.get_children())} 个匹配项")
    
    def show_details(self, event=None):
        """显示选中物品的详细信息"""
        selected = self.tree.focus()
        if not selected:
            return
        
        # 获取选中的物品ID
        item_id = selected
        
        # 确保主窗口可见
        self.root.deiconify()
        
        detail_win = ItemDetailWindow(self.root, item_id, is_primary=True,settings=self.settings)
        
        # 应用设置到详情窗口
        if hasattr(detail_win, 'apply_settings'):
            detail_win.apply_settings(self.settings)
        
        # 窗口关闭回调
        detail_win.protocol("WM_DELETE_WINDOW", lambda: self.on_detail_close(detail_win))

    def on_detail_close(self, window):
        """详情窗口关闭时的处理"""
        window.destroy()
        self.root.deiconify()